package servlet.form.calc;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CalcServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1. 요청파라미터
		
		String operator = request.getParameter("operator");
		double firstNum = Double.parseDouble(request.getParameter("firstNum"));
		double secondNum = Double.parseDouble(request.getParameter("secondNum"));
		//2. 비지니스로직(계산)
		double result = calc(firstNum,secondNum,operator);
		
		//3. 응답처리
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html><body>");
		out.println("result : " + result);
		out.println("</body></html>");
		
	}
		
		public double calc(double firstNum, double secondNum, String operator){
			
			if(operator.equals("+")) {
				return firstNum + secondNum;
			}
			else if(operator.equals("-")){
				return firstNum - secondNum;
			}
			else if(operator.equals("*")){
				return firstNum * secondNum;
			}
			else if(operator.equals("/")){
				return firstNum / secondNum;
			}
			return -999999;
			
		}
		
		
		public double calc(String firstNum, String secondNum, String operator){
			BigDecimal result = null;
			BigDecimal op1 = new BigDecimal(firstNum);
			BigDecimal op2 = new BigDecimal(secondNum);
			
			if(operator.equals("+")) {
				result=op1.add(op2);
			}
			else if(operator.equals("-")){
				result=op1.subtract(op2);
			}
			else if(operator.equals("*")){
				result=op1.multiply(op2);
			}
			else if(operator.equals("/")){
				//1 - 피연산자 소숫점 이하 몇자리에서 끊을 것인지. 3.라운드모드(올림/내림/반올림)
				result=op1.divide(op2,2,BigDecimal.ROUND_HALF_UP);
				//op1/op2 - 결과: 소숫점 이하 2자리까찌 보여주고 나머지는 반올림
				//ROUND_HALF_UP : 반올림,ROUND_UP : 올림, ROUND_DOWN : 내림
				
			}
			//BigDecimal -> double
			return result.doubleValue();
		}
		}




